# coding: utf-8

"""
@version: python3.6
@author: 噢啦嘿嘿
@contact: jian.zhou@360che.com
@software: PyCharm
@file: views.py
@time: 2020/10/19 18:23
"""
import hashlib
from flask import request
from flask_login import login_required, login_user, logout_user
from application import login_manager
from . import user
from .models.User import MantisUserTable
import json
from ..user.service import user_service
from ...libs import const
from ...libs.framework import *
from ...libs.validate_params import validate_params


@user.route("/", methods=["GET"])
@login_required
def index():
    return "this is user index page"



@login_manager.user_loader
def load_user(user_id):
    return MantisUserTable.query.get(int(user_id))



# @user.route('/login', methods=['post'])
# @validate_params(params=["username", "password"])
# def login():
#     """
#     登录验证用户名密码
#     :return:  json
#     """
#     request_data = request.json
#     u, p = request_data.get('username'), request_data.get("password")
#     res = user_service.UserService.login(u, p)
#     if res[0]:
#         return result(const.SUCCESS, '成功', res[1])
#     else:
#         return result(const.FAIL_40000, res[1], res[1])
    # return result(const.EDIT_FAIL, None, res)


@user.route("/login", methods=["POST"])
@validate_params(params=["username", "password"])
def login_in():
    subject=json.loads(request.get_data(as_text=True))
    user = MantisUserTable.query.filter_by(username=subject.get("username")).first()
    if user is None or not user.password==hashlib.md5(subject.get("password").encode(encoding='UTF-8')).hexdigest():

        return result(const.Const.OPERATE_FAIL, '登录失败')
    login_user(user, remember=False)
    return result(const.SUCCESS, "登录成功")


@user.route('/user_info', methods=['get'])
@validate_params(params=["token"])
def user_info():
    """
    用户信息
    :return: 用户信息json
    """
    username = request.args.to_dict()
    if username['token'] == "Visitor":
        res = user_service.UserService.visitor_info()
        return result(const.SUCCESS, None, res)
    u_name = username['token']
    res = user_service.UserService.user_info(u_name)
    return result(const.SUCCESS, None, res)


@user.route('/handler_list', methods=['get'])
def handler_list():
    """
    开发人名列表
    :return: json
    """
    res = user_service.UserService.handler_list()
    return result(const.SUCCESS, const.QUERY_SUCCESS, res)




@user.route("/login_out", methods=["GET","POST"])
@login_required
def exit():
    logout_user()
    return result(const.SUCCESS, "退出登录")